今天分享Json的序列化和反序列化第二種方式:使用DataContractJsonSerializer類
首先要先加入參考
System.Runtime.Serialization
然後要引用專案
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
接下來建立一個Class
[DataContract]
public class Student
{
[DataMember]
public int ID { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public int Age { get; set; }
[DataMember]
public string Sex { get; set; }
}
其中Student實體中的契約 [DataMember],[DataContract],是使用DataContractJsonSerializer序列化和反序列化必須要加的,對於其他兩種方式不必加
序列化的方式
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(Student));
MemoryStream msObj = new MemoryStream();
//將序列化之後的Json格式資料寫入流中
js.WriteObject(msObj, stu);
msObj.Position = 0;
//從0這個位置開始讀取流中的資料
StreamReader sr = new StreamReader(msObj, Encoding.UTF8);
string json = sr.ReadToEnd();
sr.Close();
msObj.Close();
Console.WriteLine(json);
反序列化的方式
string toDes = json;
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(toDes)))
{
DataContractJsonSerializer deseralizer = new DataContractJsonSerializer(typeof(Student));
Student model = (Student)deseralizer.ReadObject(ms);// //反序列化ReadObject
Console.WriteLine("ID=" + model.ID);
Console.WriteLine("Name=" + model.Name);
Console.WriteLine("Age=" + model.Age);
Console.WriteLine("Sex=" + model.Sex);
}
完整的程式碼
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
namespace ConsoleTest2
{
[DataContract]
public class Student
{
[DataMember]
public int ID { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public int Age { get; set; }
[DataMember]
public string Sex { get; set; }
}
class Program
{
static void Main(string[] args)
{
Student stu = new Student()
{
ID = 1,
Name = "曹操",
Sex = "男",
Age = 1000
};
//序列化
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(Student));
MemoryStream msObj = new MemoryStream();
//將序列化之後的Json格式資料寫入流中
js.WriteObject(msObj, stu);
msObj.Position = 0;
//從0這個位置開始讀取流中的資料
StreamReader sr = new StreamReader(msObj, Encoding.UTF8);
string json = sr.ReadToEnd();
sr.Close();
msObj.Close();
Console.WriteLine(json);
//反序列化
string toDes = json;
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(toDes)))
{
DataContractJsonSerializer deseralizer = new DataContractJsonSerializer(typeof(Student));
Student model = (Student)deseralizer.ReadObject(ms);// //反序列化ReadObject
Console.WriteLine("ID=" + model.ID);
Console.WriteLine("Name=" + model.Name);
Console.WriteLine("Age=" + model.Age);
Console.WriteLine("Sex=" + model.Sex);
}
Console.ReadKey();
}
}
}
執行結果